package me.zhengjie.modules.sync;


import com.qiaofang.applet.constants.SyncProcessingStatusConstants;
import com.qiaofang.applet.service.property.domain.DataProcessingErrorLog;
import com.qiaofang.applet.service.property.domain.SyncDataQueue;
import com.qiaofang.applet.service.property.service.DataProcessingErrorLogService;
import com.qiaofang.applet.service.property.service.SyncDataQueueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import java.util.Date;

/*
* 数据解析基类
* */
@Slf4j
public abstract class ProcessingBase {
    private String dataType;

    public void setDataType(String dataType) {
        this.dataType = dataType;
    }

    @Autowired
    private SyncDataQueueService syncDataQueueService;

    @Autowired
    private DataProcessingErrorLogService dataProcessingErrorLogService;

    public void run(){
        int startPage=1;
        Page<SyncDataQueue> page=syncDataQueueService.findSyncDataQueuePage(SyncProcessingStatusConstants.UN_HANDLE,dataType,startPage,20);
        while (page.getTotalElements()>0){
            page.forEach(item->{
                processingRow(item);
            });
            page=syncDataQueueService.findSyncDataQueuePage(SyncProcessingStatusConstants.UN_HANDLE,dataType,startPage,20);
        }

    }

    private void processingRow(SyncDataQueue item){
        try {
            processing(item);
            syncDataQueueService.deleteById(item.getId());
        } catch (Exception e) {
            log.error("processingRow error",e);
            item.setProcessingStatus(SyncProcessingStatusConstants.HANDLE_FAIL);
            syncDataQueueService.save(item);
        }
    }

    protected void saveErrorLog(String body,String errorMsg,SyncDataQueue queue){
        DataProcessingErrorLog errorLog=new DataProcessingErrorLog();
        errorLog.setDataType(this.dataType);
        errorLog.setBody(body);
        errorLog.setErrorMsg(errorMsg);
        errorLog.setCreateTime(new Date());
        errorLog.setUpdateTime(new Date());
        errorLog.setCompanyUuid(queue.getCompanyUuid());
        errorLog.setCorporationCode(queue.getCorporationCode());
        errorLog.setCityCode(queue.getCityCode());
        dataProcessingErrorLogService.save(errorLog);
    }



    protected abstract void processing(SyncDataQueue syncDataQueue);
}
